import cocos
from cocos.director import director
import kytten
from dialog_node import DialogNode, DialogLayer
from localization import localize
import os

pigeons_theme = kytten.Theme(
    'data/ui_theme',
    override={
        "gui_color": [64, 128, 255, 255],
        "font_size": 14
        }
    )
pigeons_theme_big = kytten.Theme(
    'data/ui_theme',
    override={
        "gui_color": [64, 128, 255, 255],
        "font_size": 28
        }
    )



class MainMenuDialog(DialogNode):
    def __init__(self, options=None, cbak_selection_done=None):
        self.cbak_selection_done = cbak_selection_done
        localized_options = [ localize(e) for e in options ]
        self.unlocalize = dict(zip(localized_options, options))
        k_dialog = main_menu_k(localized_options,
                               on_menu_selected = self.on_menu_selected,
                               on_escape = self.on_quit)
        super(MainMenuDialog,self).__init__(k_dialog)

    def on_menu_selected(self, choice):
        uchoice = self.unlocalize[choice]
        if uchoice == "quit":
            self.on_quit()
        else:
            self.publish_main_selection_done(uchoice)

    def on_quit(self, dummy=None):
        msg = "really_quit?"
        localized_message = localize(msg)
        k_popup = kytten.PopupConfirm(
            localized_message,
            on_ok=self.really_quit,
            theme=pigeons_theme,
            window=director.window)
        dialog_layer = self.get_ancestor(DialogLayer)
        dialog_layer.add_dialog(DialogNode(k_popup))

    def really_quit(self, dummy):
        uchoice = "quit"
        self.publish_main_selection_done(uchoice)

    def publish_main_selection_done(self, uchoice):
        self.cbak_selection_done(uchoice)

def main_menu_k(localized_options, on_menu_selected=None, on_escape=None):
    # make the kytten dialog
    k_dialog = kytten.Dialog(
        window = director.window,
        #anchor = kytten.ANCHOR_LEFT, # if comented out, centered in window
        theme = pigeons_theme_big,
        on_escape = on_escape,
        content=(
            kytten.Frame(
                kytten.Menu(
                    #align = kytten.HALIGN_LEFT,
                    on_select = on_menu_selected,
                    options = localized_options
                )
            )
        ),
    ) #/kytten dialog
    return k_dialog

class GameModeDialog(DialogNode):
    def __init__(self, options=None, starting_choice=None, ord_mutators_flags=None,
                 cbak_selection_done=None, cbak_back=None):
        self.cbak_selection_done = cbak_selection_done
        self.cbak_back = cbak_back
        localized_options = [ localize(e) for e in options ]
        self.unlocalize = dict(zip(localized_options, options))
        k_dialog = game_modes_k(localized_options, starting_choice,
                                ord_mutators_flags,
                                on_selection_done = self.on_selection_done,
                                on_escape = self.on_back)
        super(GameModeDialog,self).__init__(k_dialog)

    def on_selection_done(self, choice, res_mut):
        uchoice = self.unlocalize[choice]
        self.cbak_selection_done(uchoice, res_mut)

    def on_back(self, *args):
        self.cbak_back()


def game_modes_k(localized_options, starting_choice, ord_mutators_flags,
                 on_selection_done=None, on_escape=None): 
    panel = [ kytten.Label(localize('mutators'))]#, align=kytten.HALIGN_LEFT)]
    #self.on_selection_done = on_selection_done
    for mut, flag in ord_mutators_flags:
        panel.append(kytten.Checkbox(text=localize(mut), id=mut, is_checked=flag))

    def get_results(choice):
        it = iter(panel)
        it.next()
        res = []
        for e in it:
            res.append((e.id, e.is_checked))
        on_selection_done(choice, res)
    
    #? make work starting_choice
    k_dialog = kytten.Dialog(
        window = director.window,
        #anchor = kytten.ANCHOR_LEFT, # if comented out, centered in window
        theme = pigeons_theme,
        on_escape = on_escape,
        content=(
            kytten.Frame(
                kytten.VerticalLayout(
                    align = kytten.HALIGN_LEFT,
                    content=[
                    kytten.Menu(
                        options = localized_options,
                        align = kytten.HALIGN_LEFT,
                        on_select = get_results
                    )]+
                    panel
                )
            )
        )
    ) #/kytten dialog
    return k_dialog


class PlayerSettingsDialog(DialogNode):
    def __init__(self, options=None, starting_choices=None,
                 cbak_done=None, cbak_escape=None ):
        self.cbak_done = cbak_done
##        self.cbak_escape = cbak_escape
        self.loc_choices = [localize(e) for e in starting_choices]
        self.localized_options = [ localize(e) for e in options ]
        self.unlocalize = dict(zip(self.localized_options, options))
        self.panels = []
        self.dropdowns = []
        self.hints = []
        for i in [0,1]:
            panel , dropdown, hint = self.make_player_panel(i,
                                                       self.localized_options,
                                                       self.loc_choices[i])
            self.panels.append(panel)
            self.dropdowns.append(dropdown)
            self.hints.append(hint)
        k_dialog = player_settings_k(self.panels, self.on_done, cbak_escape)
        assert isinstance(k_dialog, kytten.Dialog)
        super(PlayerSettingsDialog, self).__init__(k_dialog)            

    def selection_change(self, player_num, controller_choice):
        self.loc_choices[player_num] = controller_choice
        if self.loc_choices[1-player_num]==controller_choice:
            i = self.localized_options.index(controller_choice)
            i = (i+1)%len(self.localized_options)
            other_controller = self.localized_options[i]
            self.dropdowns[1-player_num].set_value(other_controller)
##        self.hints[player_num].set_text(localize('show_hint_%s'%controller_choice))

    def on_done(self,*args):
        controller_choices = [ self.unlocalize[key] for key in self.loc_choices]
        self.cbak_done(controller_choices)                                     

    def make_player_panel( self, player_num, loc_options, loc_choice ):
        dropdown =  (
            kytten.Dropdown(
                    id = player_num, 
                    selected = loc_choice,
                    on_select = self.selection_change,
                    options = loc_options
                    )
            )

##        hint = kytten.Document(localize('show_hint_%s'%controller_choice),
##                               width=300, height=150)

        panel = (
            kytten.VerticalLayout( content=[
                kytten.Label(localize('player_%1d'%player_num)),
                kytten.Label(localize('controller:')),
                dropdown
#               hint
            ])
        )
        return panel, dropdown, None#, hint                      
                             

def player_settings_k(panels, on_done, on_escape):
    k_dialog = kytten.Dialog(
        window = director.window,
        #anchor = kytten.ANCHOR_LEFT, # if comented out, centered in window
        theme = pigeons_theme,
        on_escape = on_escape,
        content=(
            kytten.Frame(
                kytten.VerticalLayout(
                    #align = kytten.HALIGN_LEFT,
                    content=[
                        kytten.HorizontalLayout( content=panels ),
                        kytten.Button(localize('done'), on_click=on_done)
                        ]
                    )
                )
            )
        )
    return k_dialog

def general_settings():
    k_dialog = kytten.Dialog(
        kytten.Frame(
            kytten.Scrollable(
                kytten.VerticalLayout([
                    kytten.SectionHeader("audio",align=kytten.HALIGN_LEFT ),
                    kytten.HorizontalLayout([
                        kytten.Label("general_volume"),
                        kytten.Slider(50.0, 0.0, 100.0, steps=None, on_set=on_set)
                        ]),
                    kytten.HorizontalLayout([
                        kytten.Label("sfx_volume"),
                        kytten.Slider(50.0, 0.0, 100.0, steps=None, on_set=on_set)
                        ]),
                    kytten.HorizontalLayout([
                        kytten.Label("music_volume"),
                        kytten.Slider(50.0, 0.0, 100.0, steps=None, on_set=on_set)
                        ]),
                    kytten.SectionHeader("graphics", align=kytten.HALIGN_LEFT),
                    kytten.HorizontalLayout([
                        kytten.Label("window_size"),
                        kytten.Dropdown([
                            '640 x 480',
                            '800 x 600',
                            '1024 x 768',
                            '1280 x 960'],
				on_select=on_select)
                        ])
                    ])
                )
            )
        )

def ingame_menu():
    k_dialog = kytten.Dialog(
        window=director.window,
        anchor=kytten.ANCHOR_LEFT, # if comented out, centered in window
        theme=pigeons_theme,
        on_escape=self.on_escape,
        content=(
            kytten.Frame(
                kytten.Menu(options=[
                    "main menu",
                    "player settings",
                    "general settings"
                    ],
                    align=kytten.HALIGN_LEFT,
                    on_select=self.on_test_select
                )
            )
        ),
    ) #/kytten dialog

def ingame_help(pyglet_formatted_text):
    
    document = pyglet.text.decode_attributed(pyglet_formatted_text)

##Sample:
##'''
##With {bold True}kytten{bold False}, you can harness the power of
##{underline (255, 255, 255, 255)}pyglet{underline None}'s documents in a
##scrollable window!
##
##{font_name "Courier New"}Change fonts{font_name Lucia Grande},
##{italic True}italicize your text,{italic False} and more!
##
##{align "center"}Center yourself!{align "left"}{}
##{align "right"}Or go right.{align "left"}
##
##{color (128, 255, 128, 255)}
##Express
##{color (255, 128, 128, 255)}
##yourself
##{color (128, 128, 255, 255)}
##colorfully!
##{color (255, 255, 255, 255}
##''')

    k_dialog = kytten.Dialog(
	window=window, batch=batch, group=fg_group,
	anchor=kytten.ANCHOR_CENTER,
	theme=pigeons_theme, on_escape=on_escape,
        content = (
	kytten.Frame(kytten.Document(document, width=300, height=150))
        )
    )

